package UI;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ClientReader extends  Thread {
    private final ContactPanel contactPanel;
    private Socket socket;
    private DataInputStream dis;
    public ClientReader(Socket socket, ContactPanel contactPanel) {
        this.contactPanel=contactPanel;
        this.socket = socket;
//        try {
//            if (socket != null && !socket.isClosed()) {
//                this.dis = new DataInputStream(socket.getInputStream());
//            } else {
//                System.err.println("Socket is null or closed, cannot create DataInputStream");
//            }
//        } catch (IOException e) {
//            System.err.println("Failed to create DataInputStream: " + e.getMessage());
//            e.printStackTrace();
//        }
    }

    @Override
    public void run() {


        try {
            //接受 消息  1在线人数更新的数据     2群聊消息

            //所以客户端声明协议  先接受整数  在判断消息类型
             dis=new DataInputStream(socket.getInputStream());
            while (true) {
                int type=dis.readInt();
                switch (type) {
                    case 1:
                        //在线人数更新数据
                        updataSocketOnLineUser();
                        break;
                    case 2:
                        //群聊消息
                        getMsgToWin();
                        break;
                }
            }


        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    private void updataSocketOnLineUser() throws IOException {

    //1读取有多少个在线用户
        int count=dis.readInt();
        //2循环读取多个用户信息
        List<String>onLineUsers=new ArrayList<>();
        for (int i = 0; i < count; i++) {
            String username=dis.readUTF();
            onLineUsers.add(username);
        }


        //3更新到窗口界面展示
        contactPanel.updateOnLineUsers(onLineUsers);
    }


    public void getMsgToWin() throws IOException {
        String msg= dis.readUTF();
        ChatPanel.setMsgToWin(msg);


    }
}